<template>
  <section class="todoapp">
    <todu-header @add="handAdd"></todu-header>
    <todu-main :list='list2' @del='handlDel' @state='handlestate' @changeAll='quanxuan'></todu-main>
    <todu-footer :list='list' @delCompleted='clear' :flag='flag' @changeFlag='val=>flag=val' ></todu-footer>
  </section>
</template>

<script>
import ToduFooter from "./components/ToduFooter.vue";
import ToduHeader from "./components/ToduHeader.vue";
import ToduMain from "./components/ToduMain.vue";
export default {
  components: { ToduHeader, ToduMain, ToduFooter },
  //数据
  data() {
    return {
      list:JSON.parse(localStorage.getItem("todo-list")) || [],
      flag:1
    };
  },
  //方法
  methods: {
    handlDel(id) {
      // console.log(id)
      this.list=this.list.filter(item => item.id !==id)
    },
    handAdd(todu) {
      // console.log(todu)
      // this.list.push()  //像数组末尾添加元素
      // this.list.unshift()  //向数组开头添加元素
      this.list.unshift({
        id: Date.now(),
        name:todu,
        isDone:false
      })

    },
    handlestate(id){
      // console.log(id)
      const row =this.list.find(item =>item.id ===id)
      row.isDone = !row.isDone
    },
    clear() {
      this.list=this.list.filter(item =>item.isDone===false)
    },
    quanxuan(val) {
      this.list.forEach(item =>(item.isDone=val))
    }
  },
  //计算属性
  computed:{
    list2 (){
       if(this.flag===2) {
        return this.list.filter(item =>item.isDone===false)
      }else if(this.flag===3) {
        return this.list.filter(item =>item.isDone === true)
      }else{
        return this.list
      }
    }
  },
  watch:{
    list:{
      handler(val) {
        localStorage.setItem("todo-list",JSON.stringify(val))
      },
      deep:true
    }
  }
};
</script>

<style></style>